package com.zenithsun.pic.picdetail.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.syzg.common.controller.BaseController;
import com.syzg.common.exception.BaseException;
import com.syzg.common.model.WebInfo;
import com.syzg.common.model.WebObj;
import com.syzg.common.util.FileUtil;
import com.syzg.common.util.MethodUtil;
import com.syzg.common.util.PKCreator;
import com.syzg.common.util.SearchMap;
import com.syzg.core.exception.ServiceException;
import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;
import com.zenithsun.common.image.ImageCut;
import com.zenithsun.common.image.StorageRule;
import com.zenithsun.common.util.MultipartDownLoadUtil;
import com.zenithsun.common.util.image.ImageInfo;
import com.zenithsun.common.util.image.ImageSize;
import com.zenithsun.pic.picdetail.model.Picdetail;
import com.zenithsun.pic.picdetail.service.PicdetailService;
import com.zenithsun.pic.picdownadmin.service.PicDownAdminService;
import com.zenithsun.pic.picsubject.model.Picsubject;
import com.zenithsun.pic.picsubject.service.PicsubjectService;

import net.coobird.thumbnailator.Thumbnails;

@Controller
@RequestMapping("/path/picdetail")
public class PicdetailController extends BaseController{
	
	static Logger log = LoggerFactory.getLogger(PicdetailController.class);
	
	@Resource
	private PicdetailService picdetailService;
	@Resource
	private PicsubjectService picsubjectService;
	@Resource
	private PicDownAdminService picDownAdminService;
	
	
	/**
	 * 
	 * @param webObj
	 * @param picsubjectId
	 * @param share 是否共享
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "static-access", "unchecked" })
	@RequestMapping("/listPicdetail")
	public ModelAndView listPicdetail(WebObj webObj,String picsubjectId,boolean share)throws Exception{
		ModelAndView mv = null;
		if (share) {
			//浏览量
			viewCount(picsubjectId);
			mv = new ModelAndView("/zenithsun/pic/picdetail/listPicdetailShare.jsp");
		} else {
			mv = new ModelAndView("/zenithsun/pic/picdetail/listPicdetail.jsp");
		}
		SearchMap searchMap = SearchMap.forClass(Picdetail.class);
		searchMap.eq("a.picsubject.id", picsubjectId);
		//拍照时间倒序
		searchMap.addOrder("shootingTime", searchMap.ORDER_DESC);
		List<Picdetail> lstPicdetail = picdetailService.findObjects(searchMap);
        mv.addObject("lstPicdetail",lstPicdetail);
        mv.addObject("picsubject",picdetailService.findObjectById(picsubjectId,Picsubject.class));
        return mv;
	}
	/**
	 * 给所有没有生成缩略图的生成缩略图
	 */
	@RequestMapping("/createPic")
	public void createPic(){
		SearchMap searchMap = SearchMap.forClass(Picdetail.class);
		searchMap.addOrder("shootingTime", searchMap.ORDER_DESC);
		List<Picdetail> lstPicdetail;
		try {
			lstPicdetail = picdetailService.findObjects(searchMap);
			for(int i=0; i<lstPicdetail.size(); i++) {
				Picdetail picdetail = lstPicdetail.get(i);
				String s = picdetail.getThumbnailPath();
				if(s == null || "".equals(s)) {
					String path = PicdetailController.class.getClassLoader().getResource("").getPath();
	                String rootPath = path.substring(0,path.indexOf("/WEB-INF"));
	                String relativePath = picdetail.getPath();
	                String fileType = relativePath.substring(relativePath.lastIndexOf("."));
	                String thumbnailPath = relativePath.substring(0, relativePath.lastIndexOf("."))+"_200"+fileType;
	                String storePath = rootPath + relativePath;
					File file = new File(storePath);
					String url=rootPath+thumbnailPath;
					try {
						if(file.exists() && !new File(url).exists()){
							createPic(file,url);
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
					}
					picdetail.setThumbnailPath(thumbnailPath);
					picdetailService.update(picdetail);
				}
			}
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
	
	}
	//相册浏览量
	public void viewCount(String id)throws Exception {
		Picsubject picsubject = picsubjectService.findPicsubjectById(id);
		int view = picsubject.getView();
		picsubject.setView(view+1);
		picsubjectService.update(picsubject);
		
	}
	//相册下载量
	public void downCount(String id)throws Exception {
		Picsubject picsubject = picsubjectService.findPicsubjectById(id);
		int down = picsubject.getDown();
		picsubject.setDown(down+1);
		picsubjectService.update(picsubject);
	} 
	@RequestMapping(value = "/saveSorts", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String saveSorts(String ids,String picsubjectId)
			throws Exception {
		// TODO 处理排序
		OutMessage outMessage = new OutMessage();
		try {
			String[] idArray = ids.split(",");
			SearchMap searchMap = SearchMap.forClass(Picdetail.class);
			searchMap.eq("a.picsubject.id", picsubjectId);
			@SuppressWarnings("unchecked")
			List<Picdetail> lstPicdetail = picdetailService.findObjects(searchMap);
			Picdetail detail = null;
			Map<String, Picdetail> map = new HashMap<String, Picdetail>();
			//设置为key-value方式存储，便于获取
			for (int i = 0; i < lstPicdetail.size(); i++) {
				map.put(lstPicdetail.get(i).getId() , lstPicdetail.get(i));
			}
			for (int i = 0; i < idArray.length; i++) {
				if(idArray[i] != null && !"".equals(idArray[i])){
					//根据ID获取图片
					detail =  map.get(idArray[i]);
					//设置序号
					detail.setOrderNo(i);
					//存储到待保存容器中
					picdetailService.update(detail);
				}
			}
			outMessage.setContent("记录已保存");
			outMessage.setState(OutMessageState.Success);
		} catch (Exception e) {
			// TODO 异常处理
			log.error(e.getMessage());
			outMessage.setContent("操作失败");
			outMessage.setState(OutMessageState.Fail);
		}
		return JSON.toJSONString(outMessage);
	}

	@RequestMapping("/initPicdetail")
	public ModelAndView initPicdetail(String picsubjectId) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/pic/picdetail/addPicdetail.jsp");
		try {
			mv.addObject("picdetail", new Picdetail());
			/*LoginObject loginObj = SystemUtil.getLoginObject();
			this.picdetail.setCreatePersonId(new String(loginObj.getPersonId()));
			this.picdetail.setCreator(loginObj.getPersonName());
			this.picdetail.setCreateTime(new Date());*/
			mv.addObject("picsubject",picdetailService.findObjectById(picsubjectId,Picsubject.class));
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/addPicdetail")
	public @ResponseBody String addPicdetail(Picdetail picdetail) throws Exception {
		WebObj webObj = new WebObj();
		try {
			/*
			LoginObject loginObj = SystemUtil.getLoginObject();
			this.picdetail.setCreatePersonId(new String(loginObj.getPersonId()));
			this.picdetail.setCreator(loginObj.getPersonName());
			this.picdetail.setCreateTime(new Date());
			*/
			picdetail.setId(PKCreator.getPk());
			picdetailService.create(picdetail);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("操作失败");
		}
		return new JSONObject(webObj).toString();
	}
	
	@RequestMapping("/viewPicdetail")
	public ModelAndView viewPicdetail(Picdetail picdetail,ModelAndView mv) throws Exception {
		mv.setViewName("/zenithsun/pic/picdetail/viewPicdetail.jsp");
		try {
			String id = picdetail.getId();
			Picdetail picdetailVO = picdetailService.findObjectById(id);
			//浏览量
			/*Integer hits = picdetailVO.getHits();
			picdetailVO.setHits(hits+1);
			picdetailService.update(picdetailVO);*/
			mv.addObject("picdetail",picdetailVO);
			SearchMap searchMap = SearchMap.forClass(Picsubject.class);
			mv.addObject("lstPicsubject", picdetailService.findObjects(searchMap));
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/viewPicdetailShare")
	public ModelAndView viewPicdetailShare(Picdetail picdetail,ModelAndView mv) throws Exception {
		mv.setViewName("/zenithsun/pic/picdetail/viewPicdetailShare.jsp");
		try {
			String id = picdetail.getId();
			Picdetail picdetailVO = picdetailService.findObjectById(id);
			mv.addObject("picdetail",picdetailVO);
			SearchMap searchMap = SearchMap.forClass(Picsubject.class);
			mv.addObject("lstPicsubject", picdetailService.findObjects(searchMap));
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/editPicdetail")
	public ModelAndView editPicdetail(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/pic/picdetail/editPicdetail.jsp");
		try {
			Picdetail picdetail = picdetailService.findObjectById(id);
			mv.addObject("picdetail", picdetail);
			SearchMap searchMap = SearchMap.forClass(Picsubject.class);
			mv.addObject("lstPicsubject", picdetailService.findObjects(searchMap));
			WebObj webObj = new WebObj();
			mv.addObject("webObj",webObj);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping(value="/modPicdetail",produces="application/json;charset=UTF-8")
	public @ResponseBody String modPicdetail(Picdetail picdetailVO) throws Exception {
		try {
			
			Picdetail picdetail = picdetailService.findObjectById(picdetailVO.getId());
			picdetail = (Picdetail) MethodUtil.copyProperties(picdetail, picdetailVO);
			picdetailService.update(picdetail);
			
			return JSON.toJSONString(true);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			e.printStackTrace();
		}
		return JSON.toJSONString(false);
	}
	
	@RequestMapping("/delPicdetail")
	public ModelAndView delPicdetail(String id,WebObj webObj,String picsubjectId) throws Exception {
		String[] ids = webObj.getSelectedRow();
		try {
			if(ids == null) { //删除单个
				if(id == null) {
					ids = new String[0];
				} else {
					ids = new String[]{String.valueOf(id)};
				}
			}
			String[] idsStr = new String[ids.length];
			int i = 0;
			for(String idVO: ids) {
				idsStr[i++] = new String(idVO);
			}
			picdetailService.delete(idsStr);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return listPicdetail(webObj,picsubjectId,false);
	}
	
	@RequestMapping("/initPicUpload")
	public ModelAndView initPicUpload(String picsubjectId){
		ModelAndView mv = new ModelAndView("/zenithsun/pic/picdetail/picUpload.jsp");
		try {
			mv.addObject("picsubject",picdetailService.findObjectById(picsubjectId,Picsubject.class));
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping(value="/picUpload",produces="application/json;charset=UTF-8")
	public @ResponseBody String picUpload(@RequestParam("file") CommonsMultipartFile[] files,String picsubjectId,HttpServletRequest request){
		for(int i = 0;i<files.length;i++){
            if(!files[i].isEmpty()){
                try {
                	String oriFileName = files[i].getOriginalFilename();
                    String newFileName = StorageRule.creatUUIDName(oriFileName);	
                	String path = PicdetailController.class.getClassLoader().getResource("").getPath();
                    String rootPath = path.substring(0,path.indexOf("/WEB-INF"));
                    StorageRule sr = new StorageRule(request);
                    sr.setFileName(newFileName);
                    sr.setTempStore(false);
                    String relativePath = sr.getRelativeStorePath();
                    relativePath = StorageRule.imageSavePath + relativePath;
                    String storePath = rootPath + relativePath;
                    String tmp = storePath.substring(0,storePath.lastIndexOf("/"));
                    //File file = new File(storePath);
                    FileUtil.createDirCur(tmp);
                    
                	//拿到输出流，同时重命名上传的文件
                    FileOutputStream fos = new FileOutputStream(storePath);
                    //拿到上传文件的输入流
                    InputStream fis = files[i].getInputStream();
                    
                    byte[] buffer = new byte[1024];
        		    int len = 0;
        		    while((len=fis.read(buffer)) > 0){
        		    	fos.write(buffer, 0, len);
        		    }
                    fos.flush();
                    fos.close();
                    fis.close();
              
                    
                    /*StorageRule sr = new StorageRule(request);
                    sr.setFileName(oriFileName);
                    sr.setTempStore(false);
                    String saveStoreFolder = sr.GetPicImageShowPath();
                    String relativePath = sr.getRelativeStorePath();
                    
                    picPath = saveStoreFolder + relativePath;*/
                    
                    /*String separator = "webapps";
                    picPath = picPath.substring(path.indexOf(separator) + separator.length());
                    picPath = picPath.replaceAll("\\\\", "/");
                    picPath = picPath.substring(picPath.indexOf("/zenithsun"));*/
                    //新建一条数据
                    Picdetail picdetail = getPicdetail(files[i]);
                    //生成缩略图
                    String thumbnailPath = createThumbnail(sr,files[i].getBytes());
                    picdetail.setThumbnailPath(thumbnailPath);
                    picdetail.setPath(relativePath);
                    Picsubject picsubject = new Picsubject();
                    picsubject.setId(picsubjectId);
                    picdetail.setPicsubject(picsubject);
                    picdetailService.create(picdetail);
                    //ImageCut.addWater(storePath);
                    //生成水印
                    //ImageCut.createAddWater(files[i].getBytes(), file);
                    
                } catch (Exception e) {
                	log.error(BaseException.addExceptionLog(e));
                }
            }
		}
		return new JSONObject().toString();
	}
	
	
	/**
	 * 获取图片详情数据
	 * @param mpf
	 * @param relativePath
	 * @return
	 * @throws Exception
	 */
	private Picdetail getPicdetail(MultipartFile mpf) throws Exception {
		// 将图片详情数据存储到数据库中
		Picdetail picdetail = new Picdetail();
		picdetail.setId(PKCreator.getPk());
		if (mpf != null) {
			ImageInfo imageInfo = new ImageInfo();
			imageInfo.setRemark(mpf.getOriginalFilename().substring(0,mpf.getOriginalFilename().lastIndexOf(".")));
			imageInfo.loadImgInfo(mpf.getBytes());
			picdetail.setRemark(imageInfo.getRemark());
			if (imageInfo.getArtist() != null) {
				if(imageInfo.getArtist().length() < 10){
					picdetail.setArtist(imageInfo.getArtist());
				}
			}
			picdetail.setShootingTime(imageInfo.getShootDateTime());
		}
		return picdetail;
	}
	
	@RequestMapping("/setMask")
	public @ResponseBody String setMask(String picSubjectId,String picDetailId){
		try {
			Picsubject picsubject = (Picsubject)picdetailService.findObjectById(picSubjectId,Picsubject.class);
			picsubject.setCoverId(picDetailId);
			picdetailService.update(picsubject);
			return "success";
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return "failure";
	}
	
	/*//downPictures
	@RequestMapping("/downPictures")
	public void downPictures(String picsubjectId,HttpServletRequest request,HttpServletResponse response){
		try {
			//ip
			//String ip=request.getRemoteAddr();
			//当前终端IP
			String currentIP = WebUtil.getIpAddr(request);
			//用户名
			LoginObject currentLogin = (LoginObject) request.getSession().getAttribute(SysProperties.USER_SESSION_KEY);
			String username = currentLogin.getPersonName();
			
			String ip = currentLogin.getIp();
			//下载时间
			Date downTime = new Date();
			//下载量
			Picsubject picsubject = picsubjectService.findPicsubjectById(picsubjectId);
			Integer down = picsubject.getDown();
			//浏览量
			Integer view = picsubject.getView();
			
			PicDownAdmin p = new PicDownAdmin();
			p.setIp(currentIP);
			p.setUserName(username);
			p.setDownTime(downTime);
			p.setDownNum(down);
			p.setPicsSubject(picsubject);
			p.setId(UUID.randomUUID().toString());
			picDownAdminService.create(p);
			
			
			SearchMap searchMap = SearchMap.forClass(Picdetail.class);
			searchMap.eq("a.picsubject.id", picsubjectId);
			@SuppressWarnings("unchecked")
			List<Picdetail> lstPicdetail = picdetailService.findObjects(searchMap);
			List<File> files = new ArrayList<File>();
			Picdetail picdetail = null;
			File file = null;
			File fileTxt = null;
			File pictectTxt = null;
			String picturePath = "";
			String path = PicdetailController.class.getClassLoader().getResource("").getPath();
            String rootPath = path.substring(1,path.indexOf("/WEB-INF")) ;
           // Writer out = null;
			for (int i = 0; i < lstPicdetail.size()+1; i++) {
				if(i==lstPicdetail.size()){
					 String picMessage = "相册信息："+"\r\n"+"相册名称："+picsubject.getName()+"\r\n"+
							"图片总数："+lstPicdetail.size()+"\r\n"+
							"下载量："+down+"\r\n"+"浏览量："+view+"\r\n";
					picturePath = rootPath + "/相册信息.txt";
					fileTxt = new File(picturePath);
					files.add(fileTxt);
					out = new FileWriter(picturePath);
					out.write(picMessage);
					out.close();
				}else{
					picdetail = lstPicdetail.get(i);
					//String picdetailMessage = "图片名字："+picdetail.getRemark()+"\r\n"+"浏览量："+picdetail.getHits();
					picturePath = rootPath + picdetail.getPath();
					//pictectTxt = new File(picturePath.substring(0,picturePath.lastIndexOf("."))+".txt");
					//files.add(pictectTxt);
					file = new File(picturePath);
					if(file.exists()){
						files.add(file);
						
					}
					out = new FileWriter(pictectTxt);
					out.write(picdetailMessage);
					out.close();
				}
			}
			
			//记录下载量
			downCount(picsubjectId);
			String downPath = rootPath + "/pictures[" + new SimpleDateFormat("yyyy-MM-dd HHmmss").format(new Date()) + "].rar";
			MultipartDownLoadUtil.MultipartDownload(files, downPath, request, response);
			
		} catch (Exception e) {
			// TODO 异常处理
			e.printStackTrace();
		}
	}*/
	//downPictures
		@RequestMapping("/downPictures")
		public void downPictures(String picsubjectId,String[] ids,String op,HttpServletRequest request,HttpServletResponse response){
			try {
				Picsubject picsubject = picsubjectService.findPicsubjectById(picsubjectId);
				String path = PicdetailController.class.getClassLoader().getResource("").getPath();
				String rootPath = path.substring(1,path.indexOf("/WEB-INF")) ;
				String picturePath = "";
				int fileNameLen = 80;
		        Writer out = null;
		        File pictectTxt = null;
		        HashMap<String, String> files = new HashMap<>();
		        //选中的图片
				if(op!=null&&op.equals("notall")&&ids!=null){
					for (int i = 0; i < ids.length; i++){
						Picdetail picdetail = (Picdetail) picdetailService.findObjectById(ids[i],Picdetail.class);
						picturePath = rootPath + picdetail.getPath();
						String type = picturePath.substring(picturePath.lastIndexOf("."));
						String fileName = (picdetail.getRemark() == null ? "无": picdetail.getRemark());
						if(fileName.length() > fileNameLen) {
							fileName = fileName.substring(0, fileNameLen)+"...";
							pictectTxt = new File(picturePath.substring(0,picturePath.lastIndexOf("/"))+"/"+fileName+".txt");
							out = new FileWriter(pictectTxt);
							out.write(picdetail.getRemark());
							files.put(picturePath.substring(0,picturePath.lastIndexOf("/"))+"/"+fileName+".txt", (i + 1) + "、" +fileName+".txt");
							out.close();
							
						}
						fileName = (i + 1) + "、" + fileName + type;
						files.put(picturePath, fileName);
					}
					
				}else{
					SearchMap searchMap = SearchMap.forClass(Picdetail.class);
					searchMap.eq("a.picsubject.id", picsubjectId);
					@SuppressWarnings("unchecked")
					List<Picdetail> lstPicdetail = picdetailService.findObjects(searchMap);
					Picdetail picdetail = null;
					for (int i = 0; i < lstPicdetail.size(); i++) {
						picdetail = lstPicdetail.get(i);
						picturePath = rootPath + picdetail.getPath();
						String type = picturePath.substring(picturePath.lastIndexOf("."));
						String fileName = (picdetail.getRemark() == null ? "无": picdetail.getRemark());
						if(fileName.length() > fileNameLen) {
							fileName = fileName.substring(0, fileNameLen)+"...";
							pictectTxt = new File(picturePath.substring(0,picturePath.lastIndexOf("/"))+"/"+fileName+".txt");
							out = new FileWriter(pictectTxt);
							out.write(picdetail.getRemark());
							files.put(picturePath.substring(0,picturePath.lastIndexOf("/"))+"/"+fileName+".txt", (i + 1) + "、" +fileName+".txt");
							out.close();
							
						}
						fileName = (i + 1) + "、" + fileName + type;
						files.put(picturePath, fileName);	
					}	
				}
					//记录下载量
					downCount(picsubjectId);
					String rarName = picsubject.getRemark();
					if(rarName.length() > fileNameLen) {
						rarName = rarName.substring(0, fileNameLen)+"...";
					}
					String downPath = rootPath + "/" + rarName + ".rar";
					MultipartDownLoadUtil.downLoadFiles(files, downPath, request, response);
				
				
			} catch (Exception e) {
				// TODO 异常处理
				e.printStackTrace();
			}
		}
	/**
	 * 生成不同尺寸的缩略图
	 * 
	 * @param sr
	 */
	private String createThumbnail(StorageRule sr,byte[] bs) throws Exception {
		// 生成200*167的图片
		String sourceUrl = sr.GetPicImageStorePath();
		String fileType = sourceUrl.substring(sourceUrl.lastIndexOf("."));
		String targetUrl = sourceUrl.substring(0, sourceUrl.lastIndexOf("."));
		
		ImageSize imageSize = new ImageSize(200,167);
		String minPath = StorageRule.imageSavePath+sr.getRelativeStorePath().substring(0, sr.getRelativeStorePath().lastIndexOf("."))+ "_" + imageSize.getWidth() + fileType;
		//ImageCut.createImageBySize(sourceUrl,targetUrl + "_" + imageSize.getWidth() + fileType,imageSize.getWidth(), imageSize.getHeight());
		ImageCut.createImageBySize(bs,targetUrl + "_" + imageSize.getWidth() + fileType,imageSize);
		return minPath;
	}
	
  public void createPic(File file,String targetUrl)throws IOException{
    	/*String path = ImageCut.class.getClassLoader().getResource("").getPath();
        path = path.substring(1,path.indexOf("WEB-INF")) + "zenithsun/images/watermark/";
    	String watermarkImage = "250x167.png";*/
    	InputStream inputStream=new FileInputStream(file);
    	Thumbnails.of(inputStream).width(200).height(167).outputQuality(1.0f).toFile(targetUrl);
    	inputStream.close();
    }
}
